<template>
  <div>
    <van-nav-bar title="标题" />
    <van-form @submit="onSubmit">
      <van-field
        required
        v-model="mobile"
        label="手机号"
        placeholder="手机号"
        :rules="rules.mobile"
      />
      <van-field
        required
        v-model="code"
        label="验证码"
        placeholder="验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          :disabled="isLoad"
          :loading="isLoad"
          loading-text="登陆中..."
          round
          block
          type="info"
          native-type="submit"
        >
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'

export default {
  name: 'Login',
  methods: {
    ...mapMutations('user', ['setToken']),

    // 表单提交
    async onSubmit() {
      this.isLoad = true
      // console.log('表单校验中。。。')
      try {
        const res = await userLogin(this.mobile, this.code)
        //  console.log(res)
        // this.$store.commit('setToken', res.data)
        // this.$store.commit('user/setToken', res.data)
        this.setToken(res.data)
        // 当登录成功的时候，跳转到首页
        this.$router.push('/')

        this.$toast.success(res.message + '登陆成功')
      } catch (e) {
        this.$toast.fail(e.message)
      }
      // try-catch不会影响后续代码的和执行，都会执行 这段代码
      this.isLoad = false
    }
  },
  data() {
    return {
      isLoad: false, // 是否在发请求
      mobile: '13637268276',
      code: '246810',
      rules: {
        // 手机号的校验规则
        mobile: [
          {
            required: true,
            message: '手机号不能为空！'
          },
          // 手机号的正则校验
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式不正确！'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空！'
          },
          // 验证码的正则校验
          {
            pattern: /^\d{6}$/,
            message: '验证码格式不正确！'
          }
        ]
      }
    }
  }
}
</script>

<style lang="less" scoped></style>
